<?php

class Users{
	//前缀
	const SESSION_PREFIX = 'user_';
	/**
	 * 会员注册
	 *
	 * @param unknown_type $name
	 * @param unknown_type $email
	 * @param unknown_type $mobile_phone
	 * @param unknown_type $passwd
	 * @param unknown_type $location
	 * @return unknown
	 */
	function register($data){
		//用户注册的数据
		$data['user_passwd'] = $this->passwd_md5($data['user_passwd']);
		
		$data_ext = array(
			//附加的
			'created'		=> full_date(),
			'last_time'		=> full_date(),
			'last_ip'		=> real_ip(),
			'admin_id'		=> admin_id_ajax()
		);

		$data = array_merge($data,$data_ext);

		$mUsers = M('Users');
		//返回自增id
		$id = $mUsers->add($data);
		
		//错误返回0
		if(is_numeric($id)){			
			return $id;
		}else{
			return 0;
		}
	}
	
	function login($name,$passwd,$type = 'name'){
		$mUsers = M('Users');
		$id = $mUsers->where("$type = '$name' AND disabled = 0")->getField("id");
				
		//找到id
		if(!is_null($id)){
			//加密后的密码
			$passwd_md5 = $this->passwd_md5($passwd);
			
			$find_passwd = $mUsers->where("user_id = $id AND disabled = 0")->getField("passwd");
			
			if($passwd_md5 == $find_passwd){
				//写入session
				$this->login_after($id);
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	
	/**
	 * 登录成功后写入session
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function login_after($id){
		$user = $this->get_by_user_id($id);
		if(!is_null($user)){
			$this->set_user_session($user);
		}
	}
	
	
	function get_by_user_id($id){
		
		$mUsers = M('Users');
		return $mUsers->where('user_id='.$id)
		
		->field("*,DATE_FORMAT(shop_created,'%Y-%m-%d') AS shop_created_fmt")
		->find();
		
	}
	
	
	function get_by_user_name($name){
		$mUsers = M('Users');
		return $mUsers->getByUserName($name);
	}
	
	function get_by_user_email($email){
		$mUsers = M('Users');
		return $mUsers->getByUser_Email($email);
	}
	
	/**
	 * 登录成功后，设置管理员session
	 *
	 * @param unknown_type $admin
	 */
	function set_user_session($user){
		
		$wirte_in_session = array(
			'user_id',
			'user_name',
			'real_name',
			'mobile_phone'
		);
		foreach ($user as $k => $v){
			if(in_array($k,$wirte_in_session)){
				//如果值为空NULL，或空字符串，则session写不进去
				session(self::SESSION_PREFIX.$k,$v);
			}
		}
	}
	
	
	/**
	 * 登录成功后，设置管理员session
	 *
	 * @param unknown_type $admin
	 */
	function clear_user_session(){
		
		session_destroy();
	}
	
	/**
	 * 密码加密
	 *
	 * @param unknown_type $passwd
	 * @return unknown
	 */
	function passwd_md5($passwd){
		$salt = C('PASSWD_SALT');
		return md5(md5($passwd.$salt).$salt);
	}
	
	/**
	 * 当前是否是登录状态
	 *
	 * @return unknown
	 */
	function is_logged(){
		//前缀
		$prefix = self::SESSION_PREFIX;
    	return session('?'.$prefix.'id');
	}
	
	/**
	 * 登录管理者的信息
	 *
	 * @return unknown
	 */
	function logged_info(){
		$p = self::SESSION_PREFIX;
		if($this->is_logged()){
			return array(
				'user_id' 				=> session($p.'id'),
				'user_name' 			=> session($p.'name'),
				'user_real_name' 		=> session($p.'real_name'),
				'user_mobile_phone' 	=> session($p.'mobile_phone'),
				'user_grade' 			=> session($p.'role')
			);
		}else{
			return null;
		}
	}
	
	/**
	 * 获取登录会员id
	 *
	 * @return unknown
	 */
	function user_id(){
		
		$logged_info = $this->logged_info();
		
		if(is_null($logged_info)){
			return 0;
		}else{
			return $logged_info['user_id'];
		}
	}
	
	function session_id(){
		return session_id();
	}
	
	//验证登录
	function login_check(){
		if(!$this->is_logged()){
			$reqPage = '';
			if(isset($_SERVER['REQUEST_URI'])){
				$reqPage = '?from='.urlencode($_SERVER['REQUEST_URI']);
			}
			redirect('/index.php/Member/login'.$reqPage, 0, '请登录...');
		}
	}

	/**
	 *
	 *  我添加的客户
	 */
	function my_users(){

		//如果是管理员显示全部
		$admin_id = admin_id();
		$session_roles 	= session('admin_role');

		$where = 'u.business_admin_id='.$admin_id;
		if($session_roles === 'all' || has_role('Users:index')){
			$where = ' 1 = 1 ';
		}
		
		$mUsers = M('Users');
		return $mUsers->table('users u')
		->join('plantform pf ON pf.plantform_id = u.plantform_id')
		->where($where)
		->order('u.user_id DESC')
		->field('u.*,pf.plantform_name')
		->select();
	}
	
	/**
	 *
	 *  获取所有
	 */
	function lists_all(){

		//会员列表
    	$page   	= 1;
    	$pageSize 	= PHP_INT_MAX;
    	
    	$where = array();
    	$allCount = 0;
    	 
    	return $this->lists($where,$page,$pageSize,$allCount);
	}
	
	function lists($where,$page,$pageSize,&$allCount){

		$whereSql = ' 1 = 1 ';
		if(!is_null($where)){
			foreach ($where as $k => $v){
				if($k != '' && trim($v) != ''){
					$whereSql .= " AND {$k} LIKE '%{$v}%' ";	
				}
			}
		}
		
		//开始行
		$startIndex = ($page-1) * $pageSize;
		
		//总计数
		$allCount = $this->lists_count($whereSql);
		
		$mUsers = M('Users');
		return $mUsers->table('users u')
		->join('plantform pf ON pf.plantform_id = u.plantform_id')
		->join('admin a ON a.id = u.admin_id')
		->join('admin a2 ON a2.id = u.business_admin_id')
		->where($whereSql)
		->order('u.user_id DESC')
		->limit($startIndex. ',' . $pageSize)
		->field("u.*,pf.plantform_name,
			a.real_name AS admin_real_name,
			a2.real_name AS business_admin_name,
			DATE_FORMAT(u.created,'%Y-%m-%d') AS created_fmt
			")
		->select();
	}
	
	function lists_count($whereSql){

		$mUsers = M('Users');
		return $mUsers->table('users u')
		->join('plantform pf ON pf.plantform_id = u.plantform_id')
		->join('admin a ON a.id = u.admin_id')
		->where($whereSql)
		->getField('COUNT(*)');
	}
	
	
	function update($id,$upItems){
		
		$mUsers = M('Users');
		return $mUsers -> where('user_id='.$id)->save($upItems);
	}
	
	//修改密码
	function passwd_reset($user_id,$passwd){
		
		$upItems = array(
			'passwd'	=> $this->passwd_md5($passwd),
		);
		$update_result = $this->update($user_id,$upItems);
		
		return $update_result;
	}
	//发短信验证码
	function send_mobile_verify($user_id,&$msg){
		
		$user 	= $this->get_by_id($user_id);
		
		//手机号
		$mobile = $user['mobile_phone'];
		
		$send_result = false;
		
		if($user['mobile_validate']){
			$msg = '已通过手机实名认证,无需重新认证';
		}else if(!is_mobile($mobile)){
			$msg = '手机号码格式不正确，格式:11位数字';
		}else{
			
			import("@.ORG.Sms");
    		$sms = new SMS();
    	
    		//验证码
    		$varify_code = verify_code(6);
    		
    		//验证码写入sesion
    		session('mobile_verify_code',$varify_code);
    		
    		$content = '亲爱的72客会员：'.$user['name'].' 手机实名认证验证码  '.$varify_code.' ，10分钟内认证有效';
    		
    		//发送
    		$sout = $sms->send_sms($mobile, $content,$msg);
    		
    		$send_result = $sout;	
		}
		
		return $send_result;
	}

}